package crypt

import (
	"fmt"
	"os/exec"
	"strings"
)

func Decrypt(source, salt string) string {
	res, _ := crypt(D, source, salt)
	return res
}

func Encrypt(source, salt string) string {
	res, _ := crypt(E, source, salt)
	return res
}

type Type string

const (
	D Type = "-d"
	E Type = "-e"
)

func crypt(cty Type, source, salt string) (string, error) {
	command := fmt.Sprintf("./chedApp %s '%s' | grep succResult | awk -F ' ' '{print $2}'", string(cty), source)
	if salt != "" {
		command = fmt.Sprintf("./chedApp %s '%s' -s '%s' | grep succResult | awk -F ' ' '{print $2}'", string(cty), source, salt)
	}
	cmd := exec.Command("bash", "-c", command)
	output, err := cmd.Output()
	if err != nil || len(output) == 0 {
		return "", err
	}
	return strings.TrimSuffix(string(output), "\n"), nil
}
